#!/bin/zsh -f
# Schedule once. The child records its own result independently of the Client.
emulate -L zsh
setopt NO_UNSET PIPE_FAIL
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
umask 077
readonly TRUST_UID=0
readonly WHEEL_GID=0 ADMIN_GID=80
readonly activation=/Library/FWUninstaller.sh program=/Library/filewave_uninstaller.sh
readonly plist=/Library/LaunchDaemons/com.filewave.uninstaller.plist
readonly latch=/private/var/db/com.filewave.client-offboarding-4.2.0
fail() { print -ru2 -- "FileWave uninstaller: $1"; exit 1; }
(( EUID == 0 )) || fail 'root required'
for d in / /Library /Library/LaunchDaemons /private /private/var /private/var/db; do
    [[ -d $d && ! -L $d && $(/usr/bin/stat -f %u "$d") == $TRUST_UID ]] || fail 'unsafe parent'
    mode=$(/usr/bin/stat -f %p "$d") && [[ $mode == <-> ]] || fail 'parent stat failed'
    if ! (( (8#$mode & 8#22) == 0 )); then
        gid=$(/usr/bin/stat -f %g "$d") || fail 'group unavailable'
        [[ $d == /Library && ( $gid == $ADMIN_GID || $gid == $WHEEL_GID ) ]] && (( (8#$mode & 8#7777) == 8#775 )) || fail 'unexpected writable parent'
    fi
done
for obj in / /Library /Library/LaunchDaemons /private /private/var /private/var/db "$activation" "$program" "$plist"; do
    acl=$(/bin/ls -lde "$obj") || fail 'ACL inspection failed'
    [[ $acl != *' allow '* ]] || fail 'unexpected allow ACL'
done
for f in "$activation" "$program" "$plist"; do
    [[ -f $f && ! -L $f && $(/usr/bin/stat -f '%u:%g:%l' "$f") == "$TRUST_UID:$WHEEL_GID:1" ]] || fail 'unexpected file identity'
done
[[ $(/usr/bin/stat -f %p "$activation") == 100744 && $(/usr/bin/stat -f %p "$program") == 100500 && $(/usr/bin/stat -f %p "$plist") == 100600 ]] || fail 'unexpected file permissions'
/usr/bin/cmp -s "$0" "$activation" || fail 'activation differs from installed helper'
[[ $(/usr/bin/shasum -a 256 < "$program") == '2c9c96fc76e699a9ae8acb8607adab571b9c1bcf72e964ae1bd346d43216d5d7  -' ]] || fail 'script digest mismatch'
[[ $(/usr/bin/shasum -a 256 < "$plist") == '67c77d6eb2a33d4a288208e2a9391095ceed36c681a354433b825d0c9e0c9fc8  -' ]] || fail 'job digest mismatch'
reply=$(/bin/launchctl print system/com.filewave.uninstaller 2>&1); rc=$?
absent='Could not find service "com.filewave.uninstaller" in domain for system'
(( rc == 113 )) && [[ $reply == "$absent" || $reply == $'Bad request.\n'"$absent" ]] || fail 'job loaded or status uncertain; no action'
# Durable admission, including after reboot, interrupted activation or refusal.
/bin/mkdir -m 700 "$latch" || fail 'already attempted or cannot reserve state; do not retry'
for f in "$activation" "$program" "$plist"; do
    /usr/bin/shasum -a 256 < "$f" > "$latch/${f:t}.sha256" || fail 'cannot record staged identity'
done
/bin/launchctl bootstrap system "$plist" || fail 'bootstrap failed; do not retry'
exec /bin/launchctl kickstart system/com.filewave.uninstaller
